doctor_info = ''
events_of_the_month = []
manager_calendar = false
events_of_the_day_glob = ''
globVar = {}
if(window.location.search != ''){
	manager_calendar = true
}

function submit_appointment(month, day, year, hour, min){

	event_info = {}
	event_info['first_name'] = document.getElementById('first_name_id').value
	if(event_info['first_name'] == '') { alert('You must provide your first name'); return;}
	event_info['last_name'] = document.getElementById('last_name_id').value
	if(event_info['last_name'] == '') { alert('You must provide your last name'); return;}
	event_info['phone_number'] = document.getElementById('phone_id').value
	if(event_info['phone_number'] == '') { alert('You must provide your phone number'); return;}
	event_info['email'] = document.getElementById('email_id').value
	if(event_info['email'] == '') { alert('You must provide your email'); return;}

	event_info['visit_reason'] = document.getElementById('reason_id').value
	event_info['start'] = 'new Date(' + year + ', ' + month + ', ' + day + ', ' + hour + ', ' + min + ')'
	event_info['session_type'] = globVar['session_type']

	if(globVar['session_time'] == -3600000){ //An hour
		event_info['ends'] = 'new Date(' + year + ', ' + month + ', ' + day + ', ' + (hour+1) + ', ' + min + ')'
		event_info['session_time'] = 60
	}
	else if(globVar['session_time'] == -5400000){ //90 min
		event_info['session_time'] = 90

		if(min == 0){
			event_info['ends'] = 'new Date(' + year + ', ' + month + ', ' + day + ', ' + (hour+1) + ', ' + (min+30) + ')'
		}else{
			event_info['ends'] = 'new Date(' + year + ', ' + month + ', ' + day + ', ' + (hour+2) + ', ' + (min-30) + ')'
		}
	}else{//30 min
		event_info['session_time'] = 30
		if(min == 0){
			event_info['ends'] = 'new Date(' + year + ', ' + month + ', ' + day + ', ' + (hour) + ', ' + (min+30) + ')'
		}else{
			event_info['ends'] = 'new Date(' + year + ', ' + month + ', ' + day + ', ' + (hour+1) + ', ' + min + ')'
		}
	}


	event_info['month'] = month + 1
	event_info['day'] = day
	event_info['year'] = year
	event_info['hour'] = hour
	event_info['minute'] = min

	event_info_json = specialToSafe(JSON.stringify(event_info))
	
	function submit_appointment_response(response_string){
		if(response_string == '1') {
			//window.location.reload(true);
		}
		else if(response_string != '0')
		{
			window.location.href = 'http://' + window.location.host + '/thank_you?uuid=' + response_string
		}
		else{
			alert('There are no orders today.')
		}
	}

	initialize_ajax("/on_submit_appointment?data=" + event_info_json, submit_appointment_response)

}

function doctor_remove_appointment(uuid){
	function on_removed_appoint(receved_data){
		alert(receved_data)
		window.location.reload(true);
	}

	cmd = "/doctor_remove_appointment?uuid=" + uuid
	initialize_ajax(cmd, on_removed_appoint)

}

function get_appointment_info(month,day,year,h,m, uuid){
	if(uuid != 'none'){
		eventI = get_event_from_uuid(uuid)
		first_name = eventI['first_name']
		last_name = eventI['last_name']
		phone_number = eventI['phone_number']
		email = eventI['email']
		visit_reason = eventI['visit_reason']
	}else{
		first_name = ''
		last_name = ''
		phone_number = ''
		email = ''
		visit_reason = ''
	}

	content = 'Appointment for <br>' + (month+1) + '/' + day + '/' + year + ' , '
	content += standardize_time(h, m) + '<br><br>'
	content += '<table style="width:600px;margin-bottom:30px;margin-left:40px;border: 0px solid #dddddd;font-size:20px; font-family: "Oxygen", sans-serif;">'
	content += '<tr>'
 	content += 		'<td>First Name : </td>'
	content += 		'<td><input type="text" id="first_name_id" value="' + first_name+'" maxlength="30" style="font-size:20px;"></td>'
	content += '</tr>'
	content += '<tr>'
 	content += 		'<td>Last Name : </td>'
	content += 		'<td><input type="text" id="last_name_id" value="'+last_name+'" maxlength="30" style="font-size:20px;"></td>'
	content += '</tr>'
	content += '<tr>'
 	content += 		'<td>Phone : </td>'
	content += 		'<td><input type="text" id="phone_id" value="'+phone_number+'" maxlength="30" style="font-size:20px;"></td>'
	content += '</tr>'
	content += '<tr>'
 	content += 		'<td>Email : </td>'
	content += 		'<td><input type="text" id="email_id" value="'+email+'" maxlength="30" style="font-size:20px;"></td>'
	content += '</tr>'
	content += '<tr>'
 	content += 		'<td colspan=2 style="font-size:10px;color:red;">We will email you to confirm the appointment. </td>'
	content += '</tr>'

	content += '<tr>'
 	content += 		'<td>Reason for visit: </td>'
	content += 		'<td><textarea rows="10" cols="30" id="reason_id">' + visit_reason + '</textarea></td>'
	content += '</tr>'

	if(manager_calendar == false){
		content += '<tr>'
 		content += 		'<td></td>'
		content += 		'<td style="text-align:right;">'
		callback = 'submit_appointment(' + month + ',' + day + ',' + year + ',' + h + ',' + m + ')'
		content += '<br>' + pretty_button(callback, 'submit', 100, 30, '')
		content += '</tr>'
	}else{
		callback = 'doctor_remove_appointment(\'' + uuid + '\')'
		content += '<tr>'
 		content += 		'<td></td>'
		content += 		'<td style="text-align:right;">' + pretty_button(callback, 'Cancel Appointment', 150, 30, '') + '</td>'
		content += '</tr>'
	}

	content += '</table>'

	document.getElementById('user_info').innerHTML = content
}


function get_day_view_db(d,m,y, day){
	function on_recv_day_data(receved_data){
		if(receved_data == '1') {
			alert('Oops, that did not work. Please try making an appointment by phone.')
		}
		else if(receved_data != '0')
		{
			events_of_the_day = JSON.parse(receved_data)
			for(e in events_of_the_day){
				events_of_the_day[e]['start'] = eval(events_of_the_day[e]['start'])
				events_of_the_day[e]['end'] = eval(events_of_the_day[e]['end'])
				if(manager_calendar){
					events_of_the_day[e]['url'] = 'javascript:on_view_appointment("' + events_of_the_day[e]['uuid'] + '")'
				}
				events_of_the_day_glob = events_of_the_day
			}
			display_day_view(d,m,y, day, events_of_the_day)
		}
		else{
			alert('There are no orders today.')
		}
	}

	cmd = "/get_day_data?d=" + d + '&m=' + (m+1) + '&y=' + y 
	cmd += '&uuid=' + get_link_values('uuid') + '&access=' + get_link_values('access')
	initialize_ajax(cmd, on_recv_day_data)
}

function display_day_user(d,m,y, day, events_of_the_day){
	$('#calendar').fullCalendar({

	dayClick: function(date, allDay, jsEvent, view) {

		for(e in events_of_the_day){
			out = false
			if((date - events_of_the_day[e]['start']) == 0) out = true
			if(((date - events_of_the_day[e]['start']) > 0) && ((date - events_of_the_day[e]['end']) < 0)) out = true
			if(((date - events_of_the_day[e]['start']) < 0) && ((date - events_of_the_day[e]['start']) > globVar['session_time'])) {
				out = true
			}
		

			if(out){
				alert('This time slot overlaps with another appointment, please pick another one')
				return
			}
			//events_of_the_day[e]['end']
		}

		callback = 'get_day_view_db(' + d + ',' + m + ',' + y + ',' + day + ')'
		back_button = '<br>' + pretty_button(callback, 'Back', 100, 30, '')

		document.getElementById('Back_button').innerHTML = back_button
		document.getElementById('calendar').style.display = 'none'
		document.getElementById('user_info').style.display = 'block'

		month = date.getMonth()
		day = date.getDate()
		year = date.getFullYear()
		h = date.getHours()
		m = date.getMinutes()
		get_appointment_info(month,day,year,h,m, 'none');
	},
	header: {
		left: '',
		center: 'title',
		right: ''
		//right: 'month,basicWeek,basicDay'
	},
	editable: false,
	allDaySlot: false,
	minTime: doctor_info[translate_number_to_day(day) + '_start'],    
	maxTime: doctor_info[translate_number_to_day(day) + '_end'],
	events : events_of_the_day
	});

}

function get_event_from_uuid(uuid){
	event_item = {}
	for(i in events_of_the_day_glob){
		if(events_of_the_day_glob[i]['uuid'] == uuid){
			event_item = events_of_the_day_glob[i]
		}
	}
	return event_item
}

function on_view_appointment(uuid){
	event_item = get_event_from_uuid(uuid)
	y = event_item['year']
	month = event_item['month'] - 1
	d = event_item['day']
	h = event_item['hour']
	m = event_item['minute']

	callback = 'get_day_view_db(' + d + ',' + month + ',' + y + ',' + day + ')'
	back_button = '<br>' + pretty_button(callback, 'Back', 100, 30, '')

	document.getElementById('Back_button').innerHTML = back_button
	document.getElementById('calendar').style.display = 'none'
	document.getElementById('user_info').style.display = 'block'
	get_appointment_info(month,d,y,h,m, uuid)
}

function display_day_manager(d,m,y, day, events_of_the_day){
	$('#calendar').fullCalendar({
	header: {
		left: '',
		center: 'title',
		right: ''
	},
	editable: false,
	allDaySlot: false,
	minTime: doctor_info[translate_number_to_day(day) + '_start'],    
	maxTime: doctor_info[translate_number_to_day(day) + '_end'],
	events : events_of_the_day
	});

}

function display_day_view(d,m,y, day, events_of_the_day){

	document.getElementById('calendar').style.display = 'block'
	document.getElementById('user_info').style.display = 'none'

	$('#calendar').fullCalendar('destroy')

	if(manager_calendar){ display_day_manager(d,m,y, day, events_of_the_day) }
	else{ display_day_user(d,m,y, day, events_of_the_day) }


	$('#calendar').fullCalendar('changeView','agendaDay');
	back_button = '<br>' + pretty_button('display_month_view()', 'Back', 100, 30, '')

	$('#calendar').fullCalendar( 'gotoDate', y, m, d )
	document.getElementById('introduction').innerHTML = ''
	document.getElementById('Back_button').innerHTML = back_button

}

function display_month_view(){
	 
	
	content = '<br><br>'
	if(manager_calendar == false){
		content += 'Schedule an appointment by clicking on the date of the appointment below'
		content += '<br>'
	}
	document.getElementById('introduction').innerHTML = content
	if(manager_calendar == false){
		document.getElementById('Back_button').innerHTML = '<br>' + pretty_button('pick_service_view()', 'Back', 100, 30, '') + '<br><br>'
	}

	$('#calendar').fullCalendar('destroy')
	$('#calendar').fullCalendar({

	//eventMouseover: function( event, jsEvent, view ){
	//	alert(event.date)
	//},

	dayClick: function(date, allDay, jsEvent, view) {
		d = date.getDate();
		m = date.getMonth();
		y = date.getFullYear();
		day = date.getDay();

		today = new Date();

		if(manager_calendar == false){
			ex_days = doctor_info['exception_days'].split(',')
			for(xd in ex_days){
				dm = ex_days[xd].split('/')
				if(((m+1)==dm[0]) && (d==dm[1])){
					alert('This day is closed for business, please pick another day')
					return
				}
			}

			if((today - date) > 0){
				alert('You can only make an appointment for days after today.')
				return
			}
		}

		get_day_view_db(d,m,y,day)
	},
	eventClick: function(calEvent, jsEvent, view) {
		date = calEvent.start
		d = date.getDate();
		m = date.getMonth();
		y = date.getFullYear();
		day = date.getDay();

		get_day_view_db(d,m,y,day)
    },
	
    eventSources: ['/even_fetch'],
	header: {
		left: 'prev,next today',
		center: 'title',
		right: ''
		//right: 'month,basicWeek,basicDay'
	},
	hiddenDays: doctor_info['hiddenDays'],
	events : events_of_the_month,
	editable: false
	});

}

function start_calendar(time_session, sessionType){
	sessionType = SafeStringToSpecial(sessionType)
	globVar['session_type'] = sessionType
	globVar['session_time'] = time_session

	document.getElementById('calendar').style.display = 'block'
	document.getElementById('user_info').style.display = 'none'

	function on_doctor_data(receved_data){
		total_info = JSON.parse(receved_data)
		doctor_info = total_info[0]

		if(manager_calendar){
			events_of_the_month = total_info[1]
			for(e in events_of_the_month){
				events_of_the_month[e]['start'] = eval(events_of_the_month[e]['start'])
				events_of_the_month[e]['end'] = eval(events_of_the_month[e]['end'])
			}
		}

		doctor_info['hiddenDays'] = []
		if(doctor_info['sunday_start'] == 'closed') doctor_info['hiddenDays'].push(0)
		if(doctor_info['monday_start'] == 'closed') doctor_info['hiddenDays'].push(1)
		if(doctor_info['tuesday_start'] == 'closed') doctor_info['hiddenDays'].push(2)
		if(doctor_info['wednesday_start'] == 'closed') doctor_info['hiddenDays'].push(3)
		if(doctor_info['thursday_start'] == 'closed') doctor_info['hiddenDays'].push(4)
		if(doctor_info['friday_start'] == 'closed') doctor_info['hiddenDays'].push(5)
		if(doctor_info['saturday_start'] == 'closed') doctor_info['hiddenDays'].push(6)
		
		display_month_view()
	}

	initialize_ajax("/get_doctor_data", on_doctor_data)

}

function pick_service_view(){
	session_types = []
	session_types.push({'time':-5400000, 'description' :'90 min First Time Acupuncture Session'})
	session_types.push({'time':-3600000, 'description' :'60 min Acupuncture Session'})
	session_types.push({'time':-1800000, 'description' :'30 Free min Consultation'})
	session_types.push({'time':-1800000, 'description' :'30 min Herbal Consultation'})
	session_types.push({'time':-1800000, 'description' :'30 min Cupping Massage'})
	session_types.push({'time':-1800000, 'description' :'30 min Ear Acupuncture'})

	content = '<br><br>Which Service would you like?<br>'
	for(m in session_types){
		callback = 'start_calendar(' + session_types[m]['time'] + ',\'' + specialToSafe(session_types[m]['description']) +'\')'
		title = session_types[m]['description']
		content += pretty_button(callback, title, 400, 50, 'margin-top:10px;')
	}
	document.getElementById('user_info').innerHTML = content
	document.getElementById('calendar').style.display = 'none'
	document.getElementById('user_info').style.display = 'block'
	document.getElementById('introduction').innerHTML = ''
	document.getElementById('Back_button').innerHTML = ''
}
$(document).ready(function() {

	if(manager_calendar){
		start_calendar(0, 'manager')
	}else{
		pick_service_view()
	}
});

